<template>
  <!-- 商品基本信息组件 -->
  <div>
    <el-form :model="form" label-width="130px" :rules="rules" ref="form" class="pad-t-1">
      <el-form-item label="基本信息" class="one-label">
        <!-- 排序 -->
        <el-form-item label="排序：" label-width="170px">
          <el-input v-model="form.sortNo" @keyup.native="form.sortNo = checkInputNumWithPoint(form.sortNo, 0)" class="long-input" maxlength="8" show-word-limit/>
          <div class="tips">数字越大，排序越靠前，如果为空，默认排序方式为创建时间</div>
        </el-form-item>

        <!-- 商品名称 -->
        <el-form-item label="商品名称：" label-width="170px" prop="title">
          <div class="flex long-input">
            <el-input v-model="form.title" class="long-input-2" placeholder="请输入商品名称" maxlength="100" show-word-limit style="width: 79%"/>
            <el-input v-model="form.unit" class="short-input mar-l-10" maxlength="6" show-word-limit placeholder="单位，如：个/件/包"/>
          </div>
        </el-form-item>

        <!-- 商品货号 -->
        <el-form-item label="商品货号：" label-width="170px">
          <el-input v-model="form.goodsCode" class="long-input" placeholder="请输入商品货号" maxlength="100" show-word-limit/>
        </el-form-item>

        <template v-if="fromListPage == 30">

          <!-- 海报名称 -->
          <el-form-item label="海报商品名称：" label-width="170px">
            <el-input v-model="form.posterTitle" class="long-input" maxlength="100" show-word-limit/>
          </el-form-item>

          <!-- 海报推荐语 -->
          <el-form-item label="海报商品推荐语：" label-width="170px">
            <el-input v-model="form.posterRecommend" class="long-input" maxlength="20" show-word-limit/>
          </el-form-item>

        </template>

        <!-- 商品卖点 -->
        <el-form-item label="商品卖点：" label-width="170px">
          <el-input v-model="form.sellPoint" type="textarea" :rows="3" class="long-input" maxlength="50" show-word-limit/>
          <div class="tips">用于在云店商品详情中显示的卖点介绍，字数不超过50字</div>
        </el-form-item>

        <!-- 分享文案 -->
        <el-form-item label="分享文案：" label-width="170px">
          <el-input v-model="form.shareCopy" type="textarea" :rows="3" class="long-input" maxlength="150" show-word-limit/>
        </el-form-item>

        <!-- 商品图片 -->
        <el-form-item label="商品图片：" label-width="170px" prop="goodsImages">
          <div class="flex pro-p-minheight">
            <draggable v-model="form.goodsImages" 
              dragable="true" 
              :move="getdata"
              @update="datadragEnd">
              <template v-for="(item, key) in form.goodsImages">
                <div class="pic-bar mar-r-30 flex-item" :key="key" @mouseover.stop="itemOver(key)" @mouseout.stop="itemOut(-1)">
                  <div @click="deleteImgages(item,key)">
                    <svg-icon icon-class="close" 
                      :class="{ 'active':key==curIndex || key==curHover }"
                      class="close-icon font-16 noraml-hide" />
                  </div>
                  <img class="picture" :src="item.imageUrl + '?imageView2/1/w/200/h/200/q/100'"/>
                </div>
              </template>
            </draggable>
            <el-upload v-show="form.goodsImages.length < 5" 
              list-type="picture-card" 
              action="/api/common/uploadFiles"
              accept="image/jpeg,image/gif,image/png,image/bmp" 
              name="files"
              :file-list="form.goodsImages"
              multiple
              v-loading="fileLoading" 
              :data="token"
              :show-file-list="false" 
              :limit='5'
              :on-exceed="handleExceed"
              :on-success="(res, file, fileList) => handleUploadSuccess(res, file, fileList, 'goodsImage')"
              :before-upload="(file) => beforeUpload(file, 'goodsImage')">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
          <div class="tips mar-t-3">建议尺寸：750*750像素，可以拖拽图片调整顺序，默认第一张为主图，最多上传5张（若导入商品图片数量超过5张则在小程序内只显示前5张图片）</div>
        </el-form-item>

        <!-- 单列大图 -->
        <el-form-item label="单列大图：" label-width="170px" class="upload-remove-icon">
          <div class="flex height-148 upload-remove-bar">
            <el-upload list-type="picture-card" 
              action="/api/common/uploadFiles"
              accept="image/jpeg,image/gif,image/png,image/bmp" 
              name="files" 
              v-loading="picFileLoading" 
              :data="token"
              :show-file-list="false" 
              :on-success="(res, file, fileList) => handleUploadSuccess(res, file, fileList, 'goodsPicImage')"
              :before-upload="(file) => beforeUpload(file, 'goodsPicImage')">
              <img v-if="form.picUrl" :src="form.picUrl + '?imageView2/1/w/200/h/200/q/100'" class="picture">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="close-icon width-36 height-36 flex flex-center cursor-p" @click="closeEls('picUrl')">
              <svg-icon v-if="form.picUrl" icon-class="close" class="icon font-16 noraml-hide active"/>
            </div>
          </div>
          <div class="tips mar-t-3">建议尺寸：750*410像素，最多上传1张（用于店铺装修单列大图的商品组）</div>
        </el-form-item>

        <!-- 分享图片 -->
        <el-form-item label="分享图片：" label-width="170px" class="upload-remove-icon">
          <div class="flex height-148 upload-remove-bar">
            <el-upload list-type="picture-card" 
              action="/api/common/uploadFiles"
              accept="image/jpeg,image/gif,image/png,image/bmp" 
              name="files" 
              v-loading="shareFileLoading" 
              :data="token"
              :show-file-list="false" 
              :on-success="(res, file, fileList) => handleUploadSuccess(res, file, fileList, 'goodsShareImage')"
              :before-upload="(file) => beforeUpload(file, 'goodsShareImage')">
              <img v-if="form.shareImageUrl" :src="form.shareImageUrl + '?imageView2/1/w/200/h/200/q/100'" class="picture">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="close-icon width-36 height-36 flex flex-center cursor-p" @click="closeEls('shareImageUrl')">
              <svg-icon v-if="form.shareImageUrl" icon-class="close" class="icon font-16 noraml-hide active"/>
            </div>
          </div>
          <div class="tips mar-t-3">建议尺寸：750*750像素</div>
        </el-form-item>

        <!-- 商品海报 -->
        <el-form-item label="商品海报：" label-width="170px" class="upload-remove-icon">
          <div class="flex height-148">
            <el-upload list-type="picture-card" 
              action="/api/common/uploadFiles"
              accept="image/jpeg,image/gif,image/png,image/bmp" 
              name="files" 
              v-loading="posterFileLoading" 
              :data="token" 
              :show-file-list="false"
              :on-success="(res, file, fileList) => handleUploadSuccess(res, file, fileList, 'goodsPosterImage')"
              :before-upload="(file) => beforeUpload(file, 'goodsPosterImage')">
              <img v-if="form.posterImageUrl" :src="form.posterImageUrl + '?imageView2/1/w/200/h/200/q/100'" class="picture">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="close-icon width-36 height-36 flex flex-center cursor-p" @click="closeEls('posterImageUrl')">
              <svg-icon v-if="form.posterImageUrl" icon-class="close" class="icon font-16 noraml-hide active" />
            </div>
          </div>
          <div class="tips">
            <span>建议尺寸：750*1067像素</span>
            <el-popover placement="top" width="600" trigger="click">
              <img :src="goodsSharePoster" alt="" style="width:100%">
              <el-button slot="reference" type="text" class="mar-l-10">效果演示</el-button>
            </el-popover>
          </div>
        </el-form-item>

        <!-- 商品来源 -->
        <el-form-item label="商品来源：" label-width="170px">
          <template v-if="form.goodsSource != '1'">
            <el-select v-model="form.goodsSource" :disabled="true">
              <el-option v-for="(val, key) in dict.goodsSource" :key="key" :label="val" :value="key"></el-option>
            </el-select>
          </template>
          <template v-else>
            <el-select v-model="form.supplierId" :disabled="true">
              <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName" :value="item.supplierId"></el-option>
            </el-select>
          </template>
        </el-form-item>

        <!-- 商品品牌 -->
        <el-form-item label="商品品牌：" label-width="170px">
          <el-select v-model="form.brandId" placeholder="请选择" clearable>
            <el-option v-for="item in listBrands" :key="item.brandId" :label="item.brandName" :value="item.brandId">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 企业配置category_separate是否进行类目分类 -->
        <template v-if="fromListPage === 30 || enterpriseConfig.categorySeparate == 0">
          <el-form-item :label="(fromListPage == 30 ? '零售' : '批发') + '商品分类：'" label-width="170px" prop="goodscategoryIds">
            <el-cascader v-model="form.goodscategoryIds" 
              @change="categoryChange" 
              placeholder="选择商品分类"
              class="default-input" 
              :options="categoryData" 
              :props="{ checkStrictly: true }" 
              clearable
              filterable>
            </el-cascader>
            <div class="tips">
              <span class="mar-r-10">请选择分类</span> 
              <a class="font-blue" href="javascript:void(0)" @click="dialogCategoryTreeVisible = true">设置分类</a> 
              <span>|</span>
              <a class="font-blue" href="javascript:void(0)" @click="refreshCategory">刷新</a>
            </div>
          </el-form-item>
        </template>

        <template v-else>
          <!-- 企业配置 wholesaleCategoryAlias 判断是否使用别名 -->
          <el-form-item label="批发商品分类：" label-width="170px" prop="wholesaleGoodscategoryIds">
            <el-cascader v-model="form.wholesaleGoodscategoryIds" 
              @change="categoryChange" 
              placeholder="选择批发商品分类"
              class="default-input" 
              :options="enterpriseConfig.wholesaleCategoryAlias == 1 ? wholesaleCategoryData : categoryData" 
              :props="{ checkStrictly: true }"
              filterable>
            </el-cascader>
            <div class="tips">
              <span class="mar-r-10">请选择分类</span> 
              <a class="font-blue" href="javascript:void(0)" @click="dialogCategoryTreeVisible = true">设置分类</a> 
              <span>|</span>
              <a class="font-blue" href="javascript:void(0)" @click="refreshCategory">刷新</a>
            </div>
          </el-form-item>
        </template>

        <!-- 商品状态 -->
        <template v-if="fromListPage == 30">
          <el-form-item label="商品状态：" label-width="170px" prop="goodsStatus">
            <div class="flex-col">
              <div class="flex self-center">
                <div>
                  <el-radio v-model="form.goodsStatus" label="1" @change="doChangeStatus">上架</el-radio>
                </div>
                <div v-if="form.goodsStatus === '1'" class="mar-l-20 flex">
                  <el-checkbox v-model="taskForm.timingCheckedDown">定时下架</el-checkbox>
                  <div v-if="taskForm.timingCheckedDown">
                    <el-popover placement="top" width="245" trigger="click" v-model="visiblePopover">
                      <div>
                        <span class="flex width-per-100 mar-b-15 flex-center">设置定时下架时间</span>
                        <el-date-picker v-model="taskForm.viewOpeningTime" 
                          value-format="yyyy-MM-dd HH:mm:ss" 
                          type="datetime"
                          placeholder="选择日期时间">
                        </el-date-picker>
                        <div class="mar-t-10 flex-center">
                          <el-button @click="doCancel">取消</el-button>
                          <el-button type="primary" @click="doConfirm">确定</el-button>
                        </div>
                      </div>
                      <el-button slot="reference" icon="el-icon-edit" class="mar-l-10"></el-button>
                    </el-popover>
                    <span class="mar-l-10 font-color-9">{{ form.openingTime }}</span>
                  </div>
                </div>
              </div>
              <div class="flex self-center">
                <div>
                  <el-radio v-model="form.goodsStatus" label="0" @change="doChangeStatus">下架</el-radio>
                </div>
                <div v-if="form.goodsStatus === '0'" class="mar-l-20 flex">
                  <el-checkbox v-model="taskForm.timingCheckedUp">定时上架</el-checkbox>
                  <div v-if="taskForm.timingCheckedUp">
                    <el-popover placement="top" width="245" trigger="click" v-model="visiblePopover">
                      <div>
                        <span class="flex width-per-100 mar-b-15 text-c flex-center">设置定时上架时间</span>
                        <el-date-picker v-model="taskForm.viewOpeningTime" 
                          type="datetime" 
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择日期时间">
                        </el-date-picker>
                        <div class="mar-t-10 flex-center">
                          <el-button @click="doCancel">取消</el-button>
                          <el-button type="primary" @click="doConfirm">确定</el-button>
                        </div>
                      </div>
                      <el-button slot="reference" icon="el-icon-edit" class="mar-l-10"></el-button>
                    </el-popover>
                    <span class="mar-l-10 font-color-9">{{ form.openingTime }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="状态：" label-width="170px">
            <el-radio v-model="form.wholesaleGoodsStatus" label="1">上架</el-radio>
            <el-radio v-model="form.wholesaleGoodsStatus" label="0">下架</el-radio>
          </el-form-item>
        </template>

      </el-form-item>
    </el-form>

    <div>
      <el-dialog width="75%" v-el-drag-dialog title="设置分类" :visible.sync="dialogCategoryTreeVisible">
        <div class="el-dialog-div">
          <goods-category />
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" class="next-step-btn" @click="refreshCategory">确定</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>


<script>
  import {
    listGoodsCategory,
    listWholesaleGoodsCategory
  } from '@/api/goods/goods'
  import { listBrand } from '@/api/user/enterpriseBrand'
  import { listSupplier } from '@/api/user/supplier'
  import { getToken } from '@/utils/auth'

  import elDragDialog from '@/directive/el-dragDialog'
  import draggable from 'vuedraggable'
  import goodsBus from '@/views/goods/edit/goods-bus'
  import goodsCategory from '../../../goods-category'
  import goodsSharePoster from '@/assets/images/goods_share_poster.png'

  export default {
    mixins: [goodsBus],
    components: {
      draggable,
      goodsCategory
    },
    directives: {
      elDragDialog
    },
    props: {
      // 跳转源 30：零售 31：批发
      fromListPage: {
        type: Number,
        default: 30
      },
      // 商品对象
      goodsObj: {
        type: Object
      }
    },
    data() {
      // 名称规则
      const titleRule = (rule, value, callback) => {
        if (!this.form.title) {
          return callback(new Error('请填写商品名称'))
        }
        if (!this.form.unit) {
          return callback(new Error('请填写单位'))
        }
        callback()
      }
      // 商品图片规则
      const goodsImagesRule = (rule, value, callback) => {
        if (this.form.goodsImages.length === 0) {
          return callback(new Error('请上传商品图片'))
        }
        callback()
      }
      // 零售商品分类规则
      const goodscategoryIdsRule = (rule, value, callback) => {
        if (this.fromListPage === 30) {
          if (this.form.goodscategoryIds.length === 0) {
            return callback(new Error('请选择零售商品分类'))
          }
        }
        callback()
      }
      // 批发商品分类规则
      const wholesaleGoodscategoryIdsRule = (rule, value, callback) => {
        if (this.fromListPage === 31) {
          if (this.form.wholesaleGoodscategoryIds.length === 0) {
            return callback(new Error('请选择批发商品分类'))
          }
        }
        callback()
      }
      // 商品状态规则
      const goodsStatusRule = (rule, value, callback) => {
        const haveTaskFlag = this.taskForm.timingCheckedDown || this.taskForm.timingCheckedUp
        if (haveTaskFlag) {
          // 未修改过flag
          const unChangedFlag = this.$utils.isExist(this.form.timeUploadOrDown) && this.taskForm.oldTimeUploadOrDown === this.form.timeUploadOrDown && this.taskForm.oldOpeningTime === this.form.openingTime
          if (unChangedFlag) {
            return callback()
          }
          const time = this.form.openingTime || this.taskForm.viewOpeningTime
          if (!time) {
            return callback(new Error('请设置定时时间'))
          }
          const nowTime = new Date().getTime()
          if ((nowTime + 300000) > new Date(time).getTime()) {
            return callback(new Error('开启时间必须大于当前时间5分钟'))
          }
        }
        callback()
      }
      return {
        curIndex: -1,
        curHover: -1,
        token: {},
        // 海报效果图
        goodsSharePoster,
        // 表单
        form: {
          sortNo: '0', // 排序
          title: '', // 标题
          unit: '件', // 单位
          goodsCode: '', // 商品货号
          posterTitle: '', // 海报商品名称
          posterRecommend: '', // 海报商品推荐语
          sellPoint: '', // 商品卖点
          shareCopy: '', // 分享文案
          goodsType: '', // 商品类型
          goodsImages: [], // 商品图片列表
          labelTypes: [], // 1: 推荐, 2: 热门,3: 新品4: 包邮
          shareImageUrl: '', // 分享图片
          picUrl: '', // 单列大图
          posterImageUrl: '', // 商品海报
          goodscategoryIds: [], // 商品分类
          wholesaleGoodscategoryIds: [], // 批发商品分类
          goodsSource: '0', // 商品来源 0企业 1供应商 2淘宝商品 3供货联盟
          supplierId: '', // 供应商id
          brandId: '', // 品牌id
          goodsStatus: '0', // 零售商品状态
          wholesaleGoodsStatus: '0', // 批发商品状态
          isGoodsTiming: 0, // 定时上下架开关
          timeUploadOrDown: '', // 定时上下架类型
          openingTime: '' // 定时时间
        },
        // 定时表单
        taskForm: {
          timingCheckedDown: false,
          timingCheckedUp: false,
          viewOpeningTime: '',
          oldTimeUploadOrDown: '', // 临时变量，存储的定时标识
          oldOpeningTime: '' // 临时变量，存储的定时时间
        },
        // 数据字典
        dict: {
          goodsSource: {}
        },
        // 企业配置
        enterpriseConfig: {
          categorySeparate: '0',
          wholesaleCategoryAlias: '0'
        },
        // 表单规则
        rules: {
          title: [
            { required: true, trigger: 'blur', validator: titleRule }
          ],
          goodsImages: [
            { required: true, trigger: 'blur', validator: goodsImagesRule }
          ],
          goodscategoryIds: [
            { required: true, trigger: 'change', validator: goodscategoryIdsRule }
          ],
          wholesaleGoodscategoryIds: [
            { required: true, trigger: 'change', validator: wholesaleGoodscategoryIdsRule }
          ],
          goodsStatus: [
            { required: true, trigger: 'change', validator: goodsStatusRule }
          ]
        },
        // 文件loading
        fileLoading: false,
        shareFileLoading: false,
        picFileLoading: false,
        posterFileLoading: false,
        dialogCategoryTreeVisible: false,
        visiblePopover: false,
        // 供应商列表
        supplierList: [],
        // 品牌列表
        listBrands: [],
        // 零售商品分类
        categoryData: [],
        // 批发商品类目
        wholesaleCategoryData: []
      }
    },
    created() {
    },
    mounted() {
      const goodsBaseData = this.$store.state.goodsBaseData
      Object.assign(this.enterpriseConfig, goodsBaseData.enterpriseConfig)
      Object.assign(this.dict, goodsBaseData.dict)

      this.token = { accessToken: getToken() }
      const enterpriseId = this.getEnterpriseId()
      // 获取品牌
      listBrand(enterpriseId).then(response => {
        if (response.isError) return
        this.listBrands = response.data
      })
      this.listGoodsCategory()
      this.listWholesaleGoodsCategory()
      this.initForm()
    },
    methods: {
      // 初始化表单
      initForm() {
        if (this.goodsObj.goodsId || this.goodsObj.goodsSyncHistoryId) {
          Object.assign(this.form, this.goodsObj)
          this.form.sortNo = this.form.sortNo.toString()
          this.form.goodsSource = this.form.goodsSource.toString()
          this.form.goodsStatus = this.form.goodsStatus.toString()
          this.form.wholesaleGoodsStatus = this.form.wholesaleGoodsStatus.toString()
          // 零售商品类目
          var arr = []
          arr.push(this.goodsObj.oneCategoryId)
          arr.push(this.goodsObj.twoCategoryId)
          arr.push(this.goodsObj.threeCategoryId)
          // 批发商品类目
          var wholesaleArr = []
          wholesaleArr.push(this.goodsObj.wholesaleOneCategoryId)
          wholesaleArr.push(this.goodsObj.wholesaleTwoCategoryId)
          wholesaleArr.push(this.goodsObj.wholesaleThreeCategoryId)
  
          this.form.goodscategoryIds = arr.filter(item => item)
          this.form.wholesaleGoodscategoryIds = wholesaleArr.filter(item => item)

          // 商品定时上下架
          if (this.form.isGoodsTiming === 1) {
            this.taskForm.timingCheckedDown = this.form.timeUploadOrDown === 0
            this.taskForm.timingCheckedUp = this.form.timeUploadOrDown === 1
            this.taskForm.oldTimeUploadOrDown = this.form.timeUploadOrDown
            this.taskForm.oldOpeningTime = this.form.openingTime
          }
          if (this.form.goodsSource === '1') {
            listSupplier({ enterpriseId: this.getEnterpriseId() }).then((response) => {
              if (response.isError) return
              this.supplierList = response.data
            })
          }
        }
      },
      // 定时确定事件
      doConfirm() {
        this.form.openingTime = this.taskForm.viewOpeningTime
        this.visiblePopover = false
      },
      // 定时取消事件
      doCancel() {
        this.visiblePopover = false
      },
      // 商品状态切换事件
      doChangeStatus(value) {
        this.$refs['form'].clearValidate('goodsStatus')
        this.taskForm.timingCheckedDown = false
        this.taskForm.timingCheckedUp = false
        this.form.openingTime = ''
      },
      // 获取类目
      listGoodsCategory() {
        listGoodsCategory(this.getEnterpriseId()).then(response => {
          this.categoryData = response.data
        })
      },
      // 获取批发商品类目
      listWholesaleGoodsCategory() {
        listWholesaleGoodsCategory(this.getEnterpriseId()).then(response => {
          this.wholesaleCategoryData = response.data
        })
      },
      // 图片上传前校验
      beforeUpload(file, pictureType) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'
        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
          return false
        }
        if (pictureType === 'goodsImage') {
          this.fileLoading = true
        }
        if (pictureType === 'goodsPicImage') {
          this.picFileLoading = true
        }
        if (pictureType === 'goodsShareImage') {
          this.shareFileLoading = true
        }
        if (pictureType === 'goodsPosterImage') {
          this.posterFileLoading = true
        }
        return true
      },
      // 文件超出个数限制时的钩子
      handleExceed(file, fileList) {
        // debugger
        this.$message({ type: 'error', message: '商品图片最多5张' })
      },
      // 图片上传成功后处理
      handleUploadSuccess(res, file, fileList, pictureType) {
        if (pictureType === 'goodsImage') {
          this.fileLoading = false
        }
        if (pictureType === 'goodsPicImage') {
          this.picFileLoading = false
        }
        if (pictureType === 'goodsShareImage') {
          this.shareFileLoading = false
        }
        if (pictureType === 'goodsPosterImage') {
          this.posterFileLoading = false
        }

        if (res.code === 101) {
          const imageUrl = res.data[0]
          if (pictureType === 'goodsImage') {
            const goodsImages = this.$utils.deepClone(fileList)
            goodsImages.forEach((item) => {
              if (item.response) {
                item.imageUrl = item.response.data[0]
              }
            })
            this.form.goodsImages = goodsImages
            this.$refs['form'].clearValidate('goodsImages')
          }
          if (pictureType === 'goodsPicImage') {
            this.form.picUrl = imageUrl
          }
          if (pictureType === 'goodsShareImage') {
            this.form.shareImageUrl = imageUrl
          }
          if (pictureType === 'goodsPosterImage') {
            this.form.posterImageUrl = imageUrl
          }
        } else {
          this.$message({ type: 'error', message: res.msg })
        }
      },
      // 拖拽中事件
      getdata(evt) {},
      // 拖拽结束事件
      datadragEnd(evt) {
        evt.preventDefault()
        const filters = this.form.goodsImages
        for (let a = 0; a < filters.length; a++) {
          filters[a].index = a
        }
        this.form.goodsImages = filters
      },
      // 鼠标移入事件
      itemOver(index) {
        this.curHover = index
      },
      // 鼠标移出事件
      itemOut(index) {
        this.curHover = index
      },
      // 删除图片
      deleteImgages(item, key) {
        const goodsImages = this.form.goodsImages
        goodsImages.splice(key, 1)
        this.form.goodsImages = goodsImages
        this.$refs['form'].validateField('goodsImages')
      },
      // 图片删除事件
      closeEls(item) {
        if (item === 'picUrl') {
          this.form.picUrl = ''
        }
        if (item === 'shareImageUrl') {
          this.form.shareImageUrl = ''
        }
        if (item === 'posterImageUrl') {
          this.form.posterImageUrl = ''
        }
      },
      // 分类切换事件
      categoryChange() {
        const categoryId = this.form.goodscategoryIds[this.form.goodscategoryIds.length - 1]
        this.$bus.$emit('goods.edit.categoryId', categoryId)
        const wholesaleCategoryId = this.form.wholesaleGoodscategoryIds[this.form.wholesaleGoodscategoryIds.length - 1]
        this.$bus.$emit('goods.edit.wholesaleCategoryId', wholesaleCategoryId)
      },
      // 分类刷新事件
      refreshCategory() {
        this.listGoodsCategory()
        this.$message({ message: '刷新成功', type: 'success' })
        this.dialogCategoryTreeVisible = false
      },
      // 表单校验 true：成功 false：失败
      checkForm() {
        let ret = true
        this.$refs['form'].validate((valid, result) => {
          if (!valid) {
            const propKeys = Object.keys(result)
            this.$refs['form'].fields.forEach(field => {
              const index = propKeys.indexOf(field.prop)
              if (index !== -1) {
                this.$emit('addVaildShow', field)
              }
            })
            ret = false
          }
        })
        return ret
      },
      // 提交表单
      submitForm() {
        const haveTaskFlag = this.taskForm.timingCheckedDown || this.taskForm.timingCheckedUp
        // 定时开关
        let isGoodsTiming
        let timeUploadOrDown
        if (haveTaskFlag) {
          isGoodsTiming = 1
          timeUploadOrDown = this.taskForm.timingCheckedDown ? 0 : 1
        } else {
          isGoodsTiming = 0
        }

        const goodscategoryIds = this.form.goodscategoryIds
        const oneCategoryId = goodscategoryIds[0]
        const twoCategoryId = goodscategoryIds[1]
        const threeCategoryId = goodscategoryIds[2]

        const wholesaleGoodscategoryIds = this.form.wholesaleGoodscategoryIds
        const wholesaleOneCategoryId = wholesaleGoodscategoryIds[0]
        const wholesaleTwoCategoryId = wholesaleGoodscategoryIds[1]
        const wholesaleThreeCategoryId = wholesaleGoodscategoryIds[2]

        const submitForm = {
          goodsSource: this.form.goodsSource, // 商品来源
          supplierId: this.form.supplierId, // 供应商id
          sortNo: this.form.sortNo.trim(), // 排序
          title: this.form.title.trim(), // 商品名称
          goodsCode: this.form.goodsCode.trim(), // 商品编码
          posterTitle: this.form.posterTitle.trim(), // 海报标题
          posterRecommend: this.form.posterRecommend.trim(), // 海报推荐文案
          sellPoint: this.form.sellPoint.trim(), // 商品卖点
          shareCopy: this.form.shareCopy.trim(), // 分享文案
          unit: this.form.unit.trim(), // 单位
          brandId: this.form.brandId, // 品牌id
          goodsType: this.goodsObj.goodsId ? this.goodsObj.goodsType : this.fromListPage, // 商品类型
          fromGoodsType: this.fromListPage, // 商品类型操作源
          goodsImages: this.form.goodsImages, // 图片集合
          shareImageUrl: this.form.shareImageUrl, // 分享图片
          picUrl: this.form.picUrl, // 单列大图
          posterImageUrl: this.form.posterImageUrl, // 海报图片
          oneCategoryId: oneCategoryId, // 零售一级分类id
          twoCategoryId: twoCategoryId, // 零售二级分类id
          threeCategoryId: threeCategoryId, // 零售三级分类id
          wholesaleOneCategoryId: wholesaleOneCategoryId, // 批发一级分类id
          wholesaleTwoCategoryId: wholesaleTwoCategoryId, // 批发二级分类id
          wholesaleThreeCategoryId: wholesaleThreeCategoryId, // 批发三级分类id
          labelTypes: this.form.labelTypes, // 标签集合
          goodsStatus: this.form.goodsStatus, // 零售商品状态
          wholesaleGoodsStatus: this.form.wholesaleGoodsStatus, // 批发商品状态
          isGoodsTiming: isGoodsTiming, // 定时开关
          timeUploadOrDown: timeUploadOrDown, // 定时类型
          openingTime: this.form.openingTime // 定时时间
        }
        return submitForm
      }
    }
  }
</script>

<style lang="less" scoped>
  .pro-p-minheight {
    min-height: 148px;
  }
  .noraml-hide {
    display: none !important;
  }
  .active {
    display: block !important;
  }
  .long-input {
    width: 80%;
  }
  .long-input-2 {
    min-width: 55%;
  }
  .short-input {
    width: 20%;
  }
  .default-input {
    width: 50%;
  }
  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }
  .picture {
    width: 146px;
    height: 146px;
    display: block;
  }
  .pic-bar {
    position: relative;
    display: inline-block;
    .close-icon {
      position: absolute;
      right: -30px;
      top: -11px;
      width: 31px;
      height: 40px;
      padding: 0 7px;
      cursor: pointer;
    }
    span {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 100%;
      display: block;
      color: #fff;
      text-align: center;
      padding: 3px 0;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
  }
  .el-dialog-div {
    height: 70vh;
    overflow: auto;
  }
</style>
